import React, { useEffect, useRef, useState } from "react";
import {
  Form,
  Row,
  Col,
  Button,
  Space,
  Input,
  Cascader,
  message,
  Spin,
  Select,
} from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { changeupdateState } from "@/store/modules/assStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { getGpuList, uploadGpuInfo, updateGpuInfo } from "@/api/api_gpu";
const type = "GPU";

interface ChildMethods {
  handleUpload: () => void;
}

interface Option {
  value: string;
  label: string;
  children?: Option[];
}
// 获取显卡列表
const NVIDIALIST: Option[] = [];
const AMDLIST: Option[] = [];
const GpuList = (manufacturers: string) => {
  getGpuList(manufacturers)
    .then((res) => {
      const list = res.map((item: any) => {
        return { value: item.code_name, label: item.code_name };
      });

      manufacturers === "NVIDIA"
        ? NVIDIALIST.push(...list)
        : AMDLIST.push(...list);
    })
    .catch((err) => {
      console.log(err);
    });
};

if (NVIDIALIST.length === 0) {
  GpuList("NVIDIA");
}
if (AMDLIST.length === 0) {
  GpuList("AMD");
}

const codeList: Option[] = [
  {
    value: "NVIDIA",
    label: "NVIDIA",
    children: NVIDIALIST,
  },
  {
    value: "AMD",
    label: "AMD",
    children: AMDLIST,
  },
];

function GpuItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const [form] = Form.useForm();
  const dispatch = useAppDispatch();
  useEffect(() => {
    if (!isAdd) {
      const {
        manufacturers,
        code,
        codeName,
        gpuType,
        gpuCapacity,
        interfaceType,
        memoryFrequency,
        power,
        cooling,
        price,
        score,
      } = assInfo;

      const data = {
        gpuManufacturer: [manufacturers, code],
        codeName,
        gpuType,
        gpuCapacity,
        interfaceType,
        memoryFrequency,
        power,
        cooling,
        price,
        score,
      };
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);

  //GPU TSX
  const GPU = {
    MANUFACTURERS: (
      <Form.Item
        name="gpuManufacturer"
        label="显卡厂商"
        rules={[
          {
            type: "array",
            required: true,
            message: "Please select your gpuManufacturer!",
          },
        ]}
      >
        <Cascader options={codeList} />
      </Form.Item>
    ),
    CODE_NAME: (
      <Form.Item
        name="codeName"
        label="显卡名字"
        rules={[{ required: true, message: "Please input codeName!" }]}
      >
        <Input />
      </Form.Item>
    ),
    GPU_TYPE: (
      <Form.Item
        name="gpuType"
        label="显存类型"
        rules={[{ required: true, message: "Please select gpuType!" }]}
      >
        <Select
          options={[
            { value: "GDDR6X", label: "GDDR6X" },
            { value: "GDDR6", label: "GDDR6" },
            { value: "GDDR5X", label: "GDDR5X" },
            { value: "GDDR5", label: "GDDR5" },
            { value: "GDDR4", label: "GDDR4" },
            { value: "other", label: "其他" },
          ]}
        ></Select>
      </Form.Item>
    ),
    CAPACITY: (
      <Form.Item
        name="gpuCapacity"
        label="显存容量"
        rules={[{ required: true, message: "Please select gpuCapacit!" }]}
      >
        <Select
          options={[
            { value: "24", label: "24GB" },
            { value: "16", label: "16GB" },
            { value: "12", label: "12GB" },
            { value: "10", label: "10GB" },
            { value: "8", label: "8GB" },
            { value: "6", label: "6GB" },
            { value: "4", label: "4GB" },
            { value: "other", label: "其他" },
          ]}
        ></Select>
      </Form.Item>
    ),
    INTERFACE_TYPE: (
      <Form.Item
        name="interfaceType"
        label="接口类型"
        rules={[{ required: true, message: "Please select interfaceType!" }]}
      >
        <Input />
      </Form.Item>
    ),
    MEMORYFRQUENCY: (
      <Form.Item
        name="memoryFrequency"
        label="显存频率"
        rules={[{ required: true, message: "Please input memoryFrequency!" }]}
      >
        <Input suffix="MHz" />
      </Form.Item>
    ),
    POWER: (
      <Form.Item
        name="power"
        label="功率"
        rules={[{ required: true, message: "Please input power!" }]}
      >
        <Input suffix="W" />
      </Form.Item>
    ),
    COOLING: (
      <Form.Item
        name="cooling"
        label="散热方式"
        rules={[{ required: true, message: "Please select cooling!" }]}
      >
        <Input />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };
  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();
    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加GPU信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.gpuManufacturer[0],
        code: values.gpuManufacturer[1],
        codeName: values.codeName,
        gpuType: values.gpuType,
        gpuCapacity: values.gpuCapacity,
        interfaceType: values.interfaceType,
        memoryFrequency: values.memoryFrequency,
        power: values.power,
        cooling: values.cooling,
        img_url_arr,
        price: parseFloat(values.price),
        score: parseFloat(values.score),
      };
      if (!isAdd) {
        await updateGpuInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadGpuInfo(info);
        message.success("添加成功");
      }
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{GPU.MANUFACTURERS}</Col>
          <Col span={12}>{GPU.CODE_NAME}</Col>
          <Col span={12}>{GPU.GPU_TYPE}</Col>
          <Col span={12}>{GPU.CAPACITY}</Col>
          <Col span={12}>{GPU.INTERFACE_TYPE}</Col>
          <Col span={12}>{GPU.MEMORYFRQUENCY}</Col>
          <Col span={12}>{GPU.POWER}</Col>
          <Col span={12}>{GPU.COOLING}</Col>
          <Col span={12}>{GPU.SCORE}</Col>
          <Col span={12}>{GPU.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {isAdd ? "添加" : "更新"}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default GpuItem;
